const { ipcRenderer } = require("electron");
const path = require('path');
const fs = require('fs');
const request = require('request');
const compressing = require('compressing');
const uuid = require('uuid').v1;



const isPack = ipcRenderer.sendSync('get-package-status')
let plugInPath = path.join(__dirname, (isPack ? '../../../' : '../') + 'plug-in');

let CachePath = path.join(__dirname, (isPack ? '../../../' : '../') + 'Cache');
let servicePath = {};

fs.access(plugInPath, function (error, msg) {
    if (error) fs.mkdirSync(plugInPath)
});
fs.access(CachePath, function (error, msg) {
    if (error) fs.mkdirSync(CachePath)
});

try {
    servicePath = JSON.parse(fs.readFileSync(path.join(__dirname, (isPack ? '../../../' : './') + 'servicePath.json'), 'utf-8'));
} catch (error) {
    fs.writeFileSync(path.join(__dirname, (isPack ? '../../../' : '../') + 'servicePath.json'), `{
    "service": "http://192.168.3.106:88/PowerTool/"
}`);
    servicePath = {
        "service": "http://192.168.3.106:88/PowerTool/"
    }
}





/**
 * 
 * @param {*} path 必传参数可以是文件夹可以是文件
 * @param {*} reservePath 保存path目录 path值与reservePath值一样就保存
 */
function delFile(path, reservePath) {
    if (fs.existsSync(path)) {
        if (fs.statSync(path).isDirectory()) {
            let files = fs.readdirSync(path);
            files.forEach((file, index) => {
                let currentPath = path + "/" + file;
                if (fs.statSync(currentPath).isDirectory()) {
                    delFile(currentPath, reservePath);
                } else {
                    fs.unlinkSync(currentPath);
                }
            });
            if (path != reservePath) {
                fs.rmdirSync(path);
            }
        } else {
            fs.unlinkSync(path);
        }
    }
}

const DownloadEvent = function (id, form, to, fileName, responseEvent, dataEvent, endEvent, errorEvent) {



    const req = request({
        method: 'GET',
        uri: form + fileName,
    });
    const out = fs.createWriteStream(path.join(to, fileName + '.' + id));
    req.pipe(out);
    responseEvent && req.on('response', responseEvent);
    dataEvent && req.on('data', dataEvent);
    endEvent && req.on('end', endEvent);
    errorEvent && req.on('error', errorEvent);
}


// ---- 下载类 ---- //
function StreamDownload() {
    // 声明下载过程回调函数
    this.downloadCallback = null;
    this.id = uuid();
    this.status = {
        zip: false,
        icon: false,
        config: false,
    };
};

StreamDownload.prototype.isComplete = function (key) {
    var _isComplete = this.status.zip && this.status.icon && this.status.config;
    if (_isComplete) {
        fs.renameSync(path.join(CachePath, '/config.json.' + this.id), path.join(plugInPath, '/' + key + '/config.json'));
        fs.renameSync(path.join(CachePath, '/icon.png.' + this.id), path.join(plugInPath, '/' + key + '/icon.png'));

        var version = JSON.parse(fs.readFileSync(path.join(plugInPath, '/' + key + '/config.json'), 'utf-8'));
        version.path = key;
        version.id = uuid();
        version._icon = version.icon;
        version.icon = isPack ? '../../../plug-in/' + key + '/' + version.icon : '../plug-in/' + key + '/' + version.icon;
        this.downloadCallback('success', version);
    };
};


// 下载进度
StreamDownload.prototype.showProgress = function (received, total) {
    const percentage = (received * 100) / total;
    // 用回调显示到界面上
    this.downloadCallback('progress', percentage);
};


StreamDownload.prototype.downloadZip = function (fileName, key) {
    let receivedBytes = 0;
    let totalBytes = 0;
    DownloadEvent(
        this.id,
        servicePath.service + key + '/',
        CachePath,
        fileName,
        (data) => {
            // 更新总文件字节大小
            totalBytes = parseInt(data.headers['content-length'], 10);
        },
        (chunk) => {
            // 更新下载的文件块字节大小
            receivedBytes += chunk.length;
            this.showProgress(receivedBytes, totalBytes);
        },
        () => {
            var oldPath = path.join(CachePath, fileName + '.' + this.id);
            var newName = path.join(CachePath, key);
            fs.renameSync(oldPath, newName);
            compressing.zip.uncompress(newName, plugInPath + '/' + key).then(() => {
                this.status.zip = true;
                this.isComplete(key);
                fs.unlinkSync(newName);
            }).catch(err => {
                console.error(err);
            })
        })
};
StreamDownload.prototype.downLoadIcon = function (key) {
    DownloadEvent(
        this.id,
        servicePath.service + key + '/',
        CachePath,
        'icon.png',
        null,
        null,
        () => {
            this.status.icon = true;
            this.isComplete(key);
        })
};
StreamDownload.prototype.downLoadConfig = function (key) {
    DownloadEvent(
        this.id,
        servicePath.service + key + '/',
        CachePath,
        'config.json',
        null,
        null,
        () => {
            this.status.config = true;
            this.isComplete(key);
        })
};


StreamDownload.prototype.install = function (fileName, key, callback) {
    this.downloadCallback = callback; // 注册回调函数
    this.downloadZip(fileName, key);
    this.downLoadIcon(key);
    this.downLoadConfig(key);

}

StreamDownload.prototype.destroy = function () {
    this.downloadCallback = null;
}

module.exports = StreamDownload;